import { login } from '@/api/login'
import { getToken, setToken, setCookie } from '@/utils/auth'

const user = {
  state: { token: getToken(), name: '', loading: false, avatar: '', roles: [] },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_USER_UUID: (state, uuid) => {
      state.userUuid = uuid
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    CLOSE_LOADING: (state) => {
      state.loading = false
    },
    OPEN_LOADING: (state) => {
      state.loading = true
    }
  },

  actions: {
    closeLoading: ({ commit }) => {
      commit('CLOSE_LOADING')
    },
    openLoading: ({ commit }) => {
      commit('OPEN_LOADING')
    },
    // Login
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        login(username, userInfo.password).then(response => {
          const data = response.data.results
          setToken(data.token)
          setCookie('uuid', data.userUuid)
          setCookie('username', data.username)
          commit('SET_TOKEN', data.token)
          resolve(data)
        }).catch(error => {
          reject(error)
        })
      })
    }
  }
}

export default user

// updateState(state, { payload }) {
//   return {
//     ...state,
//     ...payload
//   }
// }
